package com.gack.business.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.gack.business.model.Area;
import com.gack.business.model.City;
import com.gack.business.model.Province;
import com.gack.business.repository.AreaRepository;
import com.gack.business.repository.CityRepository;
import com.gack.business.repository.ProvinceRepository;
import com.gack.business.vo.CityItemVO;
import com.gack.business.vo.ProvinceItemVO;

/**
 * 
 * @author ws
 * 2018-5-29
 */
@Service
@Transactional
public class PlaceService implements PlaceServiceInterface{

	@Autowired
	private ProvinceRepository provinceRepository;
	@Autowired
	private CityRepository cityRepository;
	@Autowired
	private AreaRepository areaRepository;
	
	/**
	 * 查询所有省份
	 * @return
	 */
	@Override
	public List<Province> findAllProvince() {
		return provinceRepository.findAll();
	}
	
	/**
	 * 查询某省份下所有城市
	 * @param provinceId 省份id
	 * @return
	 */
	@Override
	public List<City> findCitiesByProvince(String provinceId) {
		return cityRepository.findByProvinceId(provinceId);
	}
	
	/**
	 * 查询某城市下所有城区
	 * @param cityId 城市id
	 * @return
	 */
	@Override
	public List<Area> findAreasByCity(String cityId) {
		return areaRepository.findByCityId(cityId);
	}
	
	/**
	 * 查询所有地址 省 省下的城市  城市下的城区
	 * @return
	 */
	public List<ProvinceItemVO> findProvinceItem(){
		List<ProvinceItemVO> provinceItemVOList = new ArrayList<>();
		
		List<Province> provinceList = provinceRepository.findAll();
		List<City> cityList = cityRepository.findAll();
		List<Area> areaList = areaRepository.findAll();
		
		for(Province t : provinceList){
			ProvinceItemVO piVO = new ProvinceItemVO();
			piVO.setId(t.getId());
			piVO.setName(t.getName());
			piVO.setCode(t.getCode());
			provinceItemVOList.add(piVO);
		}
		
		for(City t : cityList){
			for(ProvinceItemVO t1 : provinceItemVOList){
				if(t.getProvinceCode().equals(t1.getCode())){
					CityItemVO ciVO = new CityItemVO();
					ciVO.setId(t.getId());
					ciVO.setName(t.getName());
					ciVO.setCode(t.getCode());
					ciVO.setProvinceCode(t.getProvinceCode());
					t1.getCityList().add(ciVO);
					break;
				}
			}
		}
		
		for(Area t : areaList){
			for(ProvinceItemVO t1 : provinceItemVOList){
				boolean flag = false;
				for(CityItemVO t2 : t1.getCityList()){
					if(t.getCityCode().equals(t2.getCode())){
						t2.getAreaList().add(t);
						flag = true;
						break;
					}
				}
				if(flag){
					break;
				}
			}
		}
		
		return provinceItemVOList;
		
	}
	
}
